<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\logic;

use think\Db;
use think\facade\Cache;
use think\Log;
use Yurun\Util\HttpRequest;

class SysLogic extends BaseLogic
{
    protected $tableName = '';
    public function __construct($tableName = ''){
        parent::__construct($tableName);
    }

    /**
     * 获取 物流公司
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _getExpressList()
    {
        return Db::name('Express')->where('status', 1)->order('displayorder DESC,id ASC')->select();
    }

    public function showExpress($expressSn,$express = ''){
        if (empty($expressSn)) {
            return $this->retError('运单号不能为空');
        }

        $provide = 'kuaidi100';

        $expressCacheModel = $this->_getExpressCache($provide, $expressSn, $express);
        // 不存在缓存或者 过期时间 小于当前时间，重新获取
        if(empty($expressCacheModel) || $expressCacheModel['lasttime'] < time()){
            $text = $this->_getExpressInKuaidi100($expressSn,$express);
            $data = json_decode($text,true);
            if (empty($data)) {
                //status
                \think\facade\Log::error('快递信息获取失败 json_decode转换失败 $provide ' . $provide . ' $express ' . $express . ' $expressSn ' . $expressSn);
                return $this->retError('获取失败，请联系管理员');
            }

            if($data['status'] != 200){
                \think\facade\Log::error('快递信息获取失败 status != 200  $provide ' . $provide . ' $express ' . $express . ' $expressSn ' . $expressSn . ' 供应商返回的字符串 ' . $text);
                return $this->retError('获取失败，请联系管理员');
            }

            $expressCacheModel['datas'] = json_encode($data['data'],256);

            // 保存缓存表
            $this->_saveExpressCache($provide, $expressSn, $expressCacheModel['datas'], $express);
        }

        return $this->retSuccess('成功',json_decode($expressCacheModel['datas'],true));
    }

    /**
     * 从 快递 100 查询 物流信息
     * @param $expressSn
     * @param $express
     */
    private function _getExpressInKuaidi100($expressSn,$express)
    {
        //        $AppKey = 'd229f7a50cfc73d4';
        $http = HttpRequest::newSession();
        $baseUrl = 'http://www.kuaidi100.com/query';
        $canshu = [
            'id' => '1',
            'type' => $express,
            'postid' => $expressSn,
            'valicode' => '',
            'temp' => '0.8473523291419331',
        ];
        $http->headers(['Content-Type' => 'application/x-www-form-urlencoded']);
        $response = $http->get($baseUrl,$canshu);

        return $response->body();
    }

    /**
     * 查询数据库是否有缓存
     * @param $provide
     * @param $expressSn
     * @param string $express
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _getExpressCache($provide,$expressSn,$express = '')
    {
        $where[] = ['provide','=',$provide];
        $where[] = ['express_sn','=',$expressSn];
        if (!empty($express)) {
            $where[] = ['express','=',$express];
        }

        return Db::name('ExpressCache')->where($where)->find();
        // 延迟
//        $yanchi = (60 * 60);
//        if($model['lasttime'] > time())
    }

    /**
     * 保存缓存
     * @param $provide
     * @param $expressSn
     * @param $datas
     * @param string $express
     * @return int|string
     */
    private function _saveExpressCache($provide, $expressSn, $datas, $express = '')
    {
        // 缓存 时间 1 小时
        $yanchi = (60 * 60);
        $lasttime = time() + $yanchi;

        $where[] = ['provide','=',$provide];
        $where[] = ['express_sn','=',$expressSn];
        $where[] = ['express','=',$express];

        if(Db::name('ExpressCache')->where($where)->count() > 0){
            return Db::name('ExpressCache')->where($where)->setField([
                'datas' => (!is_string($datas) ? json_encode($datas,256) : $datas),
                'lasttime' => $lasttime,
            ]);
        }
        else{
            return Db::name('ExpressCache')->insertGetId([
                'provide' => $provide,
                'express_sn' => $expressSn,
                'express' => $express,
                'datas' => (!is_string($datas) ? json_encode($datas,256) : $datas),
                'lasttime' => $lasttime,
            ]);
        }
    }

    public function _getSysConfig(){
        $cacheKey = 'SysLogic__getSysConfig';
        $dataList = Cache::get($cacheKey);
        if (empty($dataList)) {
            $dataList = Db::name('SiteConfig')->select();
            $config = [];
            foreach ($dataList as $item) {
                $config[$item['name']] = $item['value'];
            }
            Cache::tag('system')->set($cacheKey, $config, 86400);
            $dataList = $config;
        }
        return $dataList;
    }
    public function _claerSystemSiteConfig(){
        $cacheKey = 'SysLogic__getSysConfig';
        cache($cacheKey, null);
    }

    public function _getProjectListByWhere($where,$field = '*'){
        return Db::name('Project')->field($field)->where($where)->select();
    }

    public function _getProjectConfig($projectId){
        $config = Db::name('Project')->where('id', $projectId)->value('config');
        if (empty($config)) {
            return [];
        }
        else{
            return json_decode($config, true);
        }
    }

    public function _setProjectConfig($projectId,$config){
        return Db::name('Project')->where('id', $projectId)->setField('config',json_encode($config,256));
    }

    /**
     * 获取系统配置
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _getSystemProjectConfig(){
        $configList = Db::name('SiteConfig')->select();
        if (empty($configList)) {
            return [];
        }
        else{
            $configs = [];
            foreach ($configList as $item) {
                $configs[$item['name']] = $item['value'];
            }
            return $configs;
        }
    }

    public function _sendMessage($sendMemberId,$receiveMemberId,$title,$content){
        $postData = [
            'receive_member_id' => $receiveMemberId,
            'send_member_id' => $sendMemberId,
            'title' => $title,
            'content' => $content,
            'create_time' => time(),
        ];
        return Db::name('Message')->insertGetId($postData);
    }

    public function _getMyMessageCount($memberId){
        $where[] = ['receive_member_id','=',$memberId];
        $where[] = ['delete_time','<',1];
        return Db::name('Message')->where($where)->count();
    }
    public function _getMyMessagePager($memberId,$pageIndex,$pageSize = 20){
        $where[] = ['receive_member_id','=',$memberId];
        $where[] = ['delete_time','<',1];
        return Db::name('Message')->where($where)->order('is_read ASC,create_time DESC')
            ->page($pageIndex, $pageSize)->select();
    }

    public function _getMyMessage($memberId,$messageId){
        $where[] = ['receive_member_id','=',$memberId];
        $where[] = ['id','=',$messageId];
        $where[] = ['delete_time','<',1];

        return Db::name('Message')->where($where)->find();
    }

    public function _readMyMessage($memberId,$messageId){
        $where[] = ['receive_member_id','=',$memberId];
        $where[] = ['id','=',$messageId];
        $where[] = ['delete_time','<',1];

        return Db::name('Message')->where($where)->setField([
            'is_read' => 1,
            'update_time' => time(),
        ]);
    }

    public function _delMyMessage($memberId,$messageId){
        $where[] = ['receive_member_id','=',$memberId];
        $where[] = ['id','=',$messageId];
        $where[] = ['delete_time','<',1];

        return Db::name('Message')->where($where)->setField([
            'delete_time' => time(),
        ]);
    }
}